package util;

import javax.servlet.http.*;

public class Pager {
//	전체 게시물 수
	private long totalRows;	
//	페이지당 게시물 수
	private long rowsPerPage;
//	전체 페이지 수
	private long totalPages;
//	그룹 당 표시 페이지 수
	private long pagesPerGroup;
//	전체 페이지 그룹 수
	private long totalPageGroups;	
//	현재 페이지
	private long currentPage=1;
//	현제 페이지 그룹
	private long currentPageGroup;
	
	public void init(HttpServletRequest request, long totalRows, long rowsPerPage, long pagesPerGroup) throws Exception {
		//pager.init(request, totalRows, 8, 5);
		this.totalRows = totalRows;
		this.rowsPerPage = rowsPerPage;
		this.pagesPerGroup = pagesPerGroup;
		System.out.println("rowsPerpage = "+rowsPerPage);
		totalPages = totalRows/rowsPerPage;
		//13/8
		if(totalRows%rowsPerPage != 0) totalPages++;	
		
		totalPageGroups = totalPages/pagesPerGroup;
		if(totalPages%pagesPerGroup != 0) totalPageGroups++;
		
		String strFirstPageGroup = request.getParameter("firstPageGroup");
		String strPreviousPageGroup = request.getParameter("previousPageGroup");
		String strNextPageGroup = request.getParameter("nextPageGroup");
		String strCurrentPage = request.getParameter("currentPage");	
		String strLastPageGroup = request.getParameter("lastPageGroup");
		if(strFirstPageGroup!=null) {
			currentPageGroup = 1;
			currentPage = 1;			
		} else if(strPreviousPageGroup!=null) {
			currentPageGroup = Integer.parseInt(strPreviousPageGroup);
			currentPage = (currentPageGroup-1)*pagesPerGroup + pagesPerGroup;
		} else if(strNextPageGroup!=null) {
			currentPageGroup = Integer.parseInt(strNextPageGroup);
			currentPage = (currentPageGroup-1)*pagesPerGroup + 1;
		} else if(strCurrentPage!=null) {
			currentPage = Integer.parseInt(strCurrentPage);
			currentPageGroup = ((currentPage-1)/pagesPerGroup ) + 1;			
		} else if(strLastPageGroup!=null) {
			if(totalPageGroups!=0) {
				currentPageGroup = totalPageGroups;
				currentPage = totalPages;
			} else {
				currentPageGroup = 1;
				currentPage = 1;
			}
		} else {
			currentPageGroup = 1;
			currentPage = 1;
		}
		
		HttpSession session = request.getSession();
		session.setAttribute("pager", this);
	}

	public long getCurrentPage() {
		return currentPage;
	}

	public long getCurrentPageGroup() {
		return currentPageGroup;
	}
	
	public long getTotalPageGroups() {
		return totalPageGroups;
	}
	
	public long getRowsPerPage() {
		return rowsPerPage;
	}
	
	public long getPagesPerGroup() {
		return pagesPerGroup;
	}
	
	public long getTotalPages() {
		return totalPages;
	}
	
	public long getStartPageOfCurrentPageGroup() {
		long result = (currentPageGroup-1)*pagesPerGroup + 1;
		return result;
	}
}



